package de.slothsoft.wasbinich.android.util;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;

import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.util.Base64;
import de.slothsoft.wasbinich.core.Picture;

public final class ImageUtil {

    public static Bitmap createSectionBitmap(Picture picture) {
	return convertStringToBitmap(picture.section);
    }

    public static Bitmap createBigPictureBitmap(Picture picture) {
	return convertStringToBitmap(picture.bigPicture);
    }

    public static Bitmap decodeUrlToSmallerImage(ContextWrapper context, Uri imageUrl, int newSize)
	    throws FileNotFoundException {
	// decode only the bounds, so we will get the size
	BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
	sizeOptions.inJustDecodeBounds = true;
	BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUrl), null, sizeOptions);
	int scale = findScale(sizeOptions, newSize);
	// decode with correct scale
	BitmapFactory.Options options = new BitmapFactory.Options();
	options.inSampleSize = scale;
	return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUrl), null, options);
    }

    private static int findScale(Options sizeOptions, int newSize) {
	// Find the correct scale value. It should be the power of 2.
	int width_tmp = sizeOptions.outWidth, height_tmp = sizeOptions.outHeight;
	int scale = 1;
	while (true) {
	    if (width_tmp / 2 < newSize || height_tmp / 2 < newSize) {
		break;
	    }
	    width_tmp /= 2;
	    height_tmp /= 2;
	    scale *= 2;
	}
	return scale;
    }

    public static Bitmap convertStringToBitmap(String imageData) {
	if (imageData == null || imageData.equals("")) //$NON-NLS-1$
	    return null;
	byte[] rawBytes = Base64.decode(imageData, Base64.DEFAULT);
	Bitmap result = BitmapFactory.decodeByteArray(rawBytes, 0, rawBytes.length);
	return result;
    }

    public static String convertBitmapToString(Bitmap bitmap) {
	if (bitmap == null)
	    return null;
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
	byte[] rawBytes = stream.toByteArray();
	return Base64.encodeToString(rawBytes, Base64.DEFAULT);
    }

    static String convertStreamToString(java.io.InputStream is) {
	java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); //$NON-NLS-1$
	return s.hasNext() ? s.next() : ""; //$NON-NLS-1$
    }

    private ImageUtil() {
	// hide me
    }

}
